package com.src.xyzk_personal.config;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DirectoryUnZipper extends AsyncTask<Void, Void, Void> {

    private static final int BUFFER_SIZE = 1024;
    private static final String TAG = "DirectoryUnZipper";

    private final Context context;
    private final String zipFileName;
    private final String outputDirectory;

    private static final String PREF_NAME = "MyPrefs";
    private static final String PREF_KEY_UNZIP_DONE = "unzipDone";

    public DirectoryUnZipper(Context context, String zipFileName, String outputDirectory) {
        this.context = context;
        this.zipFileName = zipFileName;
        this.outputDirectory = outputDirectory;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            unzip();
        } catch (IOException e) {
            Log.e(TAG, "Error unzipping file: " + e.getMessage());
        }
        return null;
    }

    private void unzip() throws IOException {
        InputStream inputStream = context.getAssets().open(zipFileName);
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;
        byte[] buffer = new byte[BUFFER_SIZE];

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String fileName = zipEntry.getName();
            File outputFile = new File(outputDirectory, fileName);
            if (zipEntry.isDirectory()) {
                if (!outputFile.mkdirs()) {
                    Log.e(TAG, "Failed to create directory: " + outputFile.getAbsolutePath());
                }
            } else {
                // 如果文件已经存在，则删除它
                if (outputFile.exists()) {
                    outputFile.delete();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                int count;
                while ((count = zipInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.close();
            }
            zipInputStream.closeEntry();
        }
        zipInputStream.close();
    }

    public static boolean isUnzipDone(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getBoolean(PREF_KEY_UNZIP_DONE, false);
    }

    public static void setUnzipDone(Context context, boolean unzipDone) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putBoolean(PREF_KEY_UNZIP_DONE, unzipDone).apply();
    }

}
